package com.bfxy.rabbit.producer.autoconfigure.broker;

import com.bfxy.base.rabbit.api.Message;
import com.bfxy.base.rabbit.api.MessageType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 发送具体消息实现类
 * @author linxin
 */
@Slf4j
@Component
public class RabbitBrokerImplImpl implements RabbitBroker{
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    RabbitTemplateContainer rabbitTemplateContainer;

    @Override
    public void rapidSend(Message message) {


    }

    @Override
    public void confirmSend(Message message) {
        message.setMessageType(MessageType.CONFIRM);
        sendKernel(message);
    }

    @Override
    public void reliantSend(Message message) {
        sendKernel(message);
    }

    @Override
    public void sendMessages() {

    }

    private void sendKernel(Message message){
        AsyncBaseQueue.submit(()->{
            CorrelationData correlationData =
                    new CorrelationData(String.format("%s#%s#%s",
                            message.getMessageId(),
                            System.currentTimeMillis(),
                            message.getMessageType()));
            String topic = message.getTopic();
            String routingKey = message.getRoutingKey();
            RabbitTemplate rabbitTemplate = rabbitTemplateContainer.getTemplate(message);
            rabbitTemplate.convertAndSend(topic,routingKey,message,correlationData);
            log.info("#RabbitBrokerImpl.sendKernel# send to rabbitmq, messageId: {}", message.getMessageId());
        });
    }
}
